<?php
/**
 * Created by PhpStorm.
 * User: liubao
 * Date: 2018/8/29
 * Time: 10:49
 */

namespace Qywx\Controller;


use Think\Controller;

class BaseController extends Controller
{
    /**
     * 微信授权登录
     *
     * */
    private $appId = 'ww3a51d18348816774';//我的企业ID
    private $appSecret = 'X7ZRq0fT6js8_PRY1HAmi6d2ZQV2DrtYe-x0qknS7Wk';//自建应用里的Secret
    private $agentid = '1000027';//AgentId 手动授权时scope值改为snsapi_privateinfo 后面必须有AgentId
    private $common_url = 'http://ko.joyuti.com/dms_erp/';
    private $code = '';
    private $access_token = '';
    private $user_ticket = '';
    private $UserId = '';
    private $openid = '';

    public function index($action)
    {
        $uri = urlencode($this->common_url . 'index.php?s=' . $action); //授权成功返回地址
        //下面$url请求授权登录地址,设置的是手动授权
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appId . '&redirect_uri=' . $uri . '&response_type=code&scope=snsapi_privateinfo&agentid=' . $this->agentid . '&state=STATE#wechat_redirect';
        header('Location:' . $url);
    }

    public function back()
    {
        $this->code = $_GET['code']; //接收上面url返回code，5分钟有效期
        try {
            $userInfo = $this->common();
            if (isset($userInfo)) {
                //$openId = $this->getOpenId();//获取openID（——暂时不用）
                return $userInfo;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

    //获取企业微信用户信息
    public function common()
    {
        $access_token = $this->getAccessToken();//获取token
        $user_ticket = $this->getUserInfoList();//获取基本信息里的user_ticket值
        $userInfo = $this->getUserInfoDetail();//获取登录人的详情信息
        if (isset($access_token) && isset($user_ticket) && isset($userInfo)) {
            return $userInfo;
        }
        return false;
    }

    //获取access_token
    public function getAccessToken()
    {
        $code_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $this->appId . "&corpsecret=" . $this->appSecret;
        $access_token_str = $this->curl_get($code_url);
        $access_token_list = json_decode($access_token_str, true);
        $this->access_token = $access_token_list["access_token"];//获取access_token
        if ($access_token_list['errcode'] == 0) {
            return $this->access_token;
        }
        return false;
    }

    //获取登录人基本信息
    public function getUserInfoList()
    {
        $user_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" . $this->access_token . "&code=" . $this->code;
        $userInfo_str = $this->curl_get($user_url);
        $userInfo_list = json_decode($userInfo_str, true);//get获取企业登录人基本信息
        $this->user_ticket = $userInfo_list['user_ticket'];
        $this->UserId = $userInfo_list['UserId'];
        if ($userInfo_list['errcode'] == 0) {
            return $userInfo_list;
        }
        return false;
    }

    //获取登录人的详情信息包括昵称邮箱和头像等
    public function getUserInfoDetail()
    {
        $detail_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=" . $this->access_token;//post获取详细信息
        $param = array('user_ticket' => $this->user_ticket);
        $data = json_decode($this->curl_post($detail_url, $param), true);
        if ($data['errcode'] == 0) {
            return $data;
        }
        return false;
    }

    //根据userID获取openID
    public function getOpenId()
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=" . $this->access_token;
        $param = array('userid' => $this->UserId);
        $data = json_decode($this->curl_post($url, $param), true);
        if ($data['errcode'] == 0) {
            $this->openid = $data['openid'];
        }
        return $this->openid;
    }

    /**
     * 文本消息推送
     * touser、toparty、totag不能同时为空
     * touser 成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为@all，则向该企业应用的全部成员发送
     * toparty 部门ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * totag 标签ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * safe 表示是否是保密消息，0表示否，1表示是，默认0
     * @param $touser
     * @param $toparty
     * @param string $message //推送内容
     * @return true or false
     */
    public function push_message($touser, $toparty, $message)
    {
        $url = $this->push_url();
        $params = array(
            "touser" => $touser,
            "toparty" => $toparty,
            "totag" => "",
            "msgtype" => "text",
            "agentid" => $this->agentid,
            "text" => array(
                "content" => $message
            ),
            "safe" => 0
        );
        $data = json_decode($this->curl_post($url, $params), true);
        if ($data['errcode'] == 0) {
            $this->push_log('文本消息', $message, '', $touser, $toparty);
            return true;
        }
        return false;
    }

    /**
     * //发送推送文本卡片消息展现
     * @param $touser
     * @param $toparty
     * @param $title
     * @param $description
     * @param $url
     * @return bool|mixed
     */
    public function push_card($touser, $toparty, $title, $description, $url)
    {
        $push_url = $this->push_url();
        $params = array(
            "touser" => $touser,
            "toparty" => $toparty,
            "totag" => "",
            "msgtype" => "textcard",
            "agentid" => $this->agentid,
            "textcard" => array(
                "title" => $title,
                "description" => $description,
                "url" => $url,
                "btntxt" => ""
            )
        );
        $data = json_decode($this->curl_post($push_url, $params), true);
        if ($data['errcode'] == 0) {
            $this->push_log($title, $description, $url, $touser, $toparty);
            return $data;
        }
        return false;

    }

    /**
     * 图文消息推送touser、toparty、totag不能同时为空
     * articles图文消息，一个图文消息支持1到8条图文
     * @param $touser
     * @param $toparty
     * @param $title
     * @param $description
     * @param $url
     * @param $picurl
     * @return bool|mixed
     */
    public function push_image_text($touser, $toparty, $title, $description, $url, $picurl)
    {
        $push_url = $this->push_url();
        $params = array(
            "touser" => $touser,
            "toparty" => $toparty,
            "totag" => "",
            "msgtype" => "news",
            "agentid" => $this->agentid,
            "news" => array(
                "articles" => array(
                    array(
                        "title" => $title,
                        "description" => $description,
                        "url" => $url,
                        "picurl" => $picurl,
                        "btntxt" => ""
                    )
                )

            )
        );
        $data = json_decode($this->curl_post($push_url, $params), true);
        if ($data['errcode'] == 0) {
            return $data;
        }
        return false;
    }

    //推送文本、卡片、图文消息的请求地址
    public function push_url()
    {
        $access_token = !empty($this->access_token) ? $this->access_token : $this->getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" . $access_token;
        return $url;
    }

    /**
     * 获取部门列表
     * @param $department_id //部门id。获取指定部门及其下的子部门。 如果不填，默认获取全量组织架构
     * @return bool
     */
    public function get_department($department_id)
    {
        $access_token = !empty($this->access_token) ? $this->access_token : $this->getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" . $access_token . "&id=" . $department_id;
        $departmentInfo = $this->curl_get($url);
        $departmentInfo = json_decode($departmentInfo, true);//只能拉取token对应的应用的权限范围内的部门列表
        if ($departmentInfo['errcode'] == 0) {
            return $departmentInfo['department'];//所有的部门信息
        }
        return false;

    }

    /**
     * 根据部门名称获取对应企业微信的部门id
     * @param $name //部门名称
     * @return false|int|string
     */
    public function get_department_id($name)
    {
        $departmentInfo = $this->get_department('');
        if (isset($departmentInfo)) {
            $department_id = array_search($name, array_column((array)$departmentInfo, 'name'));
            return $departmentInfo[$department_id]['id'];
        } else {
            return false;
        }
    }

    //curl get方式
    public function curl_get($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    //curl post方式
    public function curl_post($url, $param)
    {
        $param = json_encode($param, true);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        return $data;
    }

    //判断是否是企业微信登录
    public function isQyWx()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'wxwork') !== false) {
            return true;
        } else {
            return false;
        }
    }

    //推送操作日志记录
    public function push_log($title, $description, $url, $touser, $toparty)
    {
        $db_push_log = M("db_push_log");
        $log['title'] = $title;
        $log['description'] = $description;
        $log['url'] = $url;
        $log['touser'] = $touser;
        $log['toparty'] = $toparty;
        $log['add_user'] = isset($_SESSION['dms_username']) ? $_SESSION['dms_username'] : '系统发送';
        $log['add_date'] = date('Y-m-d H:i:s');
        $db_push_log->add($log);
    }


}